package com.snake.controllers;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.apache.log4j.Logger;

import com.snake.common.ReturnEnum;
import com.snake.models.ActivityAppSetting;
import com.snake.models.ActivityCard;
import com.snake.models.ActivityShareApp;
import com.snake.models.ActivityShareLink;
import com.snake.models.ActivityWinRecord;
import com.snake.models.ActivityWinRule;
import com.snake.models.Blessing;
import com.snake.models.FileFile;
import com.snake.repositories.ActivityCardService;
import com.snake.repositories.ActivityWinRecordService;
import com.snake.repositories.ActivityWinRuleService;
import com.snake.repositories.AppSettingService;
import com.snake.repositories.BlessingService;
import com.snake.repositories.FileService;
import com.snake.repositories.ShareAppService;
import com.snake.repositories.ShareLinkService;
import com.snake.util.BeanUtils;
import com.snake.util.DateUtil;

/**
 * 
 */
@RestController
@RequestMapping(value = "/api/method/blessing")
public class BlessingController extends BaseController{
	public static Logger logger = Logger.getLogger(BlessingController.class
			.getName());
	@Autowired
	private BlessingService blessingService;
	@Autowired
	private FileService fileService;
	@Autowired
	private AppSettingService appSettingService;
	@Autowired
	private ShareAppService shareAppService;
	@Autowired
	private ShareLinkService shareLinkService;
	@Autowired
	private ActivityWinRuleService activityWinRuleService;
	@Autowired
	private ActivityCardService activityCardService;
	@Autowired
	private ActivityWinRecordService activityWinRecordService;
	
	@Value("${app.fileUrl}")
	private String fileUrl;
	
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public Map<String, Object> getById(@PathVariable(value = "id") Integer id) {
		Blessing blessing = blessingService.getById(id);
		if (blessing == null) {
			return getReturnMapFailure("获取失败");
		}
		return getReturnMapSuccess(blessing);
	}
	//获取应用配置
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public Map<String, Object> getList(HttpServletRequest request) {
		Map<String, Object> params = getParameterMap(request);
		List<Blessing> blessingList = blessingService.getByList(params);
		FileFile titleUrlFile = fileService.getById(Integer.valueOf(blessingList.get(0).getTitleUrl()));
		blessingList.get(0).setTitleUrl("'"+fileUrl+"/file/getAppImgById/"
				+ Integer.valueOf(blessingList.get(0).getTitleUrl().toString())
				+ "."
				+ titleUrlFile.getFileName().split("\\.")[1] + "'");
		
		FileFile backgroundFile = fileService.getById(Integer.valueOf(blessingList.get(0).getBackground()));
		blessingList.get(0).setBackground("'"+fileUrl+"/file/getAppImgById/"
				+ Integer.valueOf(blessingList.get(0).getBackground())
				+ "."
				+ backgroundFile.getFileName().split("\\.")[1] + "'");
		
		FileFile blueFile = fileService.getById(Integer.valueOf(blessingList.get(0).getBlue()));
		blessingList.get(0).setBlue("'"+fileUrl+"/file/getAppImgById/"
				+ Integer.valueOf(blessingList.get(0).getBlue()) + "."
				+ blueFile.getFileName().split("\\.")[1] + "'");
		
		FileFile logoFile = fileService.getById(Integer.valueOf(blessingList.get(0).getLogo()));
		blessingList.get(0).setLogo("'"+fileUrl+"/file/getAppImgById/"
				+ Integer.valueOf(blessingList.get(0).getLogo()) + "."
				+ logoFile.getFileName().split("\\.")[1] + "'");
		
		FileFile redFile = fileService.getById(Integer.valueOf(blessingList.get(0).getRed()));
		blessingList.get(0).setRed("'"+fileUrl+"/file/getAppImgById/"
				+ Integer.valueOf(blessingList.get(0).getRed()) + "."
				+ redFile.getFileName().split("\\.")[1] + "'");
		
		FileFile ruleFile = fileService.getById(Integer.valueOf(blessingList.get(0).getRule()));
		blessingList.get(0).setRule("'"+fileUrl+"/file/getAppImgById/"
				+ Integer.valueOf(blessingList.get(0).getRule()) + "."
				+ ruleFile.getFileName().split("\\.")[1] + "'");
		if (blessingList.size()<=0) {
			return getReturnMapFailure("该应用配置不存在");
		}
		
		return getReturnMapSuccess(blessingList.get(0));
	}
	//获取分享配置
	@RequestMapping(value = "/getShareInfo", method = RequestMethod.GET)
	public Map<String, Object> getShareInfo(HttpServletRequest request) throws Exception {
		Map<String, Object> params = getParameterMap(request);
		//获取appseting
		List<ActivityAppSetting> appSettingList = appSettingService.getByList(params);
		if(appSettingList.size()>0){
			Integer shareType = appSettingList.get(0).getShareType();
			if(shareType==1){
				params.clear();
				params.put("appSettingId", appSettingList.get(0).getId());
				List<ActivityShareApp> byList = shareAppService.getByList(params);
				if(byList.size()>0){
					String shareHeaderImg = byList.get(0).getShareHeaderImg();
					FileFile shareHeaderImgFile = fileService.getById(Integer.valueOf(shareHeaderImg));
					byList.get(0).setShareHeaderImg("'"+fileUrl+"/file/getAppImgById/"
							+ Integer.valueOf(shareHeaderImg) + "."
							+ shareHeaderImgFile.getFileName().split("\\.")[1] + "'");
				}
				return getReturnMapSuccess(byList.get(0));
			}else if(shareType==2){
				params.clear();
				params.put("appSettingId", appSettingList.get(0).getId());
				List<ActivityShareLink> byList = shareLinkService.getByList(params);
				if(byList.size()>0){
					String shareHeaderImg = byList.get(0).getShareHeaderImg();
					FileFile shareHeaderImgFile = fileService.getById(Integer.valueOf(shareHeaderImg));
					byList.get(0).setShareHeaderImg("'"+fileUrl+"/file/getAppImgById/"
							+ Integer.valueOf(shareHeaderImg) + "."
							+ shareHeaderImgFile.getFileName().split("\\.")[1] + "'");
				}
				return getReturnMapSuccess(byList.get(0));
			}else{
				return getReturnMapFailure(ReturnEnum.SHARECONFISNULL);
			}
		}else{
			return getReturnMapFailure(ReturnEnum.SHARECONFISNULL);
		}
	}
	
	//判断应用有效期
	@RequestMapping(value = "/isValidity", method = RequestMethod.GET)
	public Map<String, Object> isValidity(HttpServletRequest request) throws Exception {
		Map<String, Object> params = getParameterMap(request);
		Map<String, Object> map = new HashMap<String, Object>();
		List<Blessing> blessingList = blessingService.getByList(params);
		if(blessingList.size()>0){
			Integer startTime = blessingList.get(0).getStartTime();
			Integer endTime = blessingList.get(0).getEndTime();
			if(startTime!=null&&startTime!=0&&endTime!=null&&endTime!=0){
				String startTimes = DateUtil.formatDate(new Date(Long.valueOf(startTime*1000)),"yyyy-MM-dd HH:mm:ss");
				String endTimes = DateUtil.formatDate(new Date(Long.valueOf(endTime*1000)),"yyyy-MM-dd HH:mm:ss");
				String date = DateUtil.formatDate(new Date(),"yyyy-MM-dd HH:mm:ss");
				boolean serviceOut = DateUtil.isServiceOut(startTimes, endTimes, date);
				map.put("isValidity", serviceOut);
				return getReturnMapSuccess(map);
			}
		}else{
			return getReturnMapFailure("该应用配置不存在");
		}
		map.put("isValidity", false);
		return getReturnMapSuccess(map);
	}
	//判断是否中奖
		@RequestMapping(value = "/isWin", method = RequestMethod.GET)
		public Map<String, Object> isWin(HttpServletRequest request) throws Exception {
			Map<String, Object> params = getParameterMap(request);
			Integer appBuyId = Integer.valueOf(params.get("appBuyId").toString());
			Integer fen = Integer.valueOf(params.get("fen").toString());
			String openId = params.get("openId").toString();
			
			// 先获取中奖配置信息activity_app_setting--activity_win_rule
			int winTimes=0;
			int winProbability=0;
			Map<String, Object> appSettingParams = new HashMap<String, Object>();
			appSettingParams.put("appBuyId", appBuyId);
			List<ActivityAppSetting> activityAppSettingList = appSettingService.getByList(appSettingParams);
			Map<String, Object> appSettingMap = BeanUtils.Bean2Map(activityAppSettingList.get(0));
			if(appSettingMap!=null){
				Map<String, Object> winRuleParams = new HashMap<String, Object>();
				winRuleParams.put("actId", Integer.valueOf(appSettingMap.get("id").toString()));
				List<ActivityWinRule> activityWinRuleList = activityWinRuleService.getByList(winRuleParams);
				Map<String, Object> winRuleMap = BeanUtils.Bean2Map(activityWinRuleList.get(0));
				if(winRuleMap!=null){
					if(winRuleMap.containsKey("winTimes")&&winRuleMap.get("winTimes").toString().equals("")){
						winTimes=Integer.valueOf(winRuleMap.get("winTimes").toString());
					}
					winProbability=Integer.valueOf(winRuleMap.get("winProbability").toString());
				}
			}
			//判断是否有卡券
			Map<String, Object> cardParams = new HashMap<String, Object>();
			cardParams.put("appBuyId", appBuyId);
			List<ActivityCard> cardList = activityCardService.getByList(cardParams);
			if(cardList.size()>0){
				// 判断是否有卡券，是否审核通过
				cardParams.put("cardStatus", 1);
				List<ActivityCard> activityCardStatusList = activityCardService.getByList(cardParams);
				if(activityCardStatusList.size()<=0){
					
				}
				int winCardId=0;
				String wxCardId="";
				// 判断该玩家是否有中奖次数activity_win_record
				Map<String, Object> winRecordParams = new HashMap<String, Object>();
				winRecordParams.put("openId", openId);
				List<ActivityWinRecord> winRecordList = activityWinRecordService.getByList(winRecordParams);
				Integer winRecordCount = winRecordList.size();
				if(winRecordCount!=null){
					if(winTimes==0||winRecordCount<winTimes){
						// 根据分值判断获取那个卡券
						for(ActivityCard card:cardList){
							if(card.getWinType().toString().equals("2")&&card.getScoreStart().toString().equals("")&&card.getScoreEnd().toString().equals("")){
								int scoreStart=Integer.valueOf(card.getScoreStart().toString());
								int scoreEnd=Integer.valueOf(card.getScoreEnd().toString());
								if(scoreStart<=fen&&fen<=scoreEnd){
									winCardId=Integer.valueOf(card.getId().toString());
									wxCardId=card.getWxCardId().toString();
								}
							}
						}
						
					}else{
						Map<String, Object> map = new LinkedHashMap<String, Object>();
						map.put("message", "未中奖");
						map.put("code", 5010);
						map.put("success", false);
						return map;
					}
				}
				// 领取的这个卡券数量减1
				if(winCardId!=0){
					ActivityCard byId = activityCardService.getById(winCardId);
					Map<String, Object> cardMap= BeanUtils.Bean2Map(byId);
					if(cardMap!=null){
						int publishCount=Integer.valueOf(cardMap.get("publishCount").toString());
						byId.setPublishCount(publishCount-1);
						ActivityCard cardUpdate = activityCardService.update(byId);
						// 保存该玩家的获奖记录activity_win_record
						ActivityWinRecord activityWinRecord=new ActivityWinRecord();
						activityWinRecord.setAppBuyId(appBuyId);
						activityWinRecord.setCardId(winCardId);
						activityWinRecord.setOpenId(openId);
						ActivityWinRecord add = activityWinRecordService.add(activityWinRecord);
						if(null!=add){
							Map<String, Object> maps = new HashMap<String, Object>();
							maps.put("cardId", winCardId);
							maps.put("wxCardId", wxCardId);
							Map<String, Object> map = new LinkedHashMap<String, Object>();
							map.put("message", "操作成功");
							map.put("code", 200);
							map.put("success", true);
							map.put("data", maps);
							return map;
						}
					}
				}
			}else{//没有卡券
				if(winProbability==0){
					Map<String, Object> map = new LinkedHashMap<String, Object>();
					map.put("message", "未中奖");
					map.put("code", 5010);
					map.put("success", false);
					return map;
				}
				// 判断该玩家是否有中奖次数activity_win_record
				Map<String, Object> winRecordParams = new HashMap<String, Object>();
				winRecordParams.put("openId", openId);
				List<ActivityWinRecord> winRecordList = activityWinRecordService.getByList(winRecordParams);
				Integer winRecordCount = winRecordList.size();
				if(winRecordCount!=null){
					if(winTimes==0||winRecordCount<winTimes){
						//根据随机值判断是否中奖
						int randomNum = new Random().nextInt(100) + 1;
						if(1<=randomNum&&randomNum>=winProbability){
							Map<String, Object> map = new LinkedHashMap<String, Object>();
							Map<String, Object> maps = new HashMap<String, Object>();
							maps.put("info", "中奖");
							map.put("message", "操作成功");
							map.put("code", 2010);
							map.put("success", false);
							map.put("data", maps);
							return map;
						}else{
							Map<String, Object> map = new LinkedHashMap<String, Object>();
							map.put("message", "未中奖");
							map.put("code", 5010);
							map.put("success", false);
							return map;
						}
					}else{
						Map<String, Object> map = new LinkedHashMap<String, Object>();
						map.put("message", "未中奖");
						map.put("code", 5010);
						map.put("success", false);
						return map;
					}
				}
			}

			System.out.println(appBuyId + "---" + fen);
			Map<String, Object> map = new LinkedHashMap<String, Object>();
			map.put("message", "系统错误");
			map.put("code", 500);
			map.put("success", false);
			return getReturnMapSuccess(map);
		}
}